package com.api.shop.interceptor;

import com.api.shop.common.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @Auther: wyx
 * @Date: 2019-04-25 9:17
 * @Description:
 */
@Slf4j
public class CORSInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("----> in CORSInterceptor");
        String method = request.getMethod();

        Enumeration<?> enumeration = request.getHeaderNames();
        while(enumeration.hasMoreElements()){
            String key = (String) enumeration.nextElement();
            String value = request.getHeader(key);
            log.info("key: {}, value: {}", key, value);
        }

        if(method.equals("OPTIONS")){
            return true;
        }

//        BufferedReader bufferedReader = null;
//        String inputLine;
//        StringBuffer str = new StringBuffer();
//        try {
//            bufferedReader = request.getReader();
//            while ((inputLine = bufferedReader.readLine()) != null){
//                str.append(inputLine);
//            }
//            bufferedReader.close();
//        }catch (Exception e){
//            log.debug("CORSException: {}", e.getMessage());
//        }
//        log.info("body: {}", str.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        RequestHolder.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
